Vue.component("yl-upload", {
  template: `<div>
    <div class="preview" v-if="Picture_URL">
        <el-image ref="FImage" class="el-upload-list__item-thumbnail" style="width: 148px; height: 148px" :preview-src-list="[base64?Picture_URL:base + Picture_URL]" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions">
            <span @click="handlePictureCardPreview('FImage')"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
  props: {
    value: {
      type: String,
      default: "",
    },
    base: {
      type: String,
      default: "",
    },
    base64: {
      type: Boolean,
      default: false,
    },
    unslider: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      Picture_URL: this.value,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      quality: 100,
    };
  },
  watch: {
    value(newVal) {
      this.Picture_URL = newVal;
    },
    Picture_URL(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    formatTooltip(val) {
      return "图片压缩比例：" + val + "%";
    },
    upload({ raw }) {
      const that = this;
      new Compressor(raw, {
        quality: that.quality / 100,
        success(file) {
          that.loading = true;
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            if (!that.base64) {
              $.ajax({
                type: "POST",
                url: DomainName + "/BusinessPIC",
                data: {
                  Data: e.target.result,
                  DataLength: file.size,
                  FileName: file.name,
                  logo: true,
                },
                complete: function (XMLHttpRequest) {
                  that.loading = false;
                  if (
                    XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT"
                  ) {
                    window.parent.document.location.href =
                      absolutepath() +
                      XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  if (Result.Status == "success") {
                    that.Picture_URL = Result.Picture_Url;
                    that.$message.success("上传成功");
                  } else {
                    that.$message.error("上传失败");
                  }
                },
                error: function () {
                  that.$message.error("操作失败，请稍后再试");
                },
                dataType: "json",
              });
            } else {
              that.Picture_URL = e.target.result;
              that.loading = false;
            }
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    handlePictureCardPreview(formName) {
      this.$refs[formName].showViewer = true;
    },
    handleRemove() {
      this.Picture_URL = "";
      this.$emit("remove");
    },
  },
});
new Vue({
  el: "#app",
  data() {
    return {
      fileList: [],
      form: {
        Expert_SerialNumber: "",
        Picture_URL: "", //表名
        Expert_Name: "",
        Expert_Type_Name: "",
        Mobile: "",
        ProvinceNumber: "",
        CityNumber: "",
        CountyNumber: "",
        Address: "",
        Notes: "",
        Children: {
          business_expert_type: [
            {
              Expert_Type_SerialNumber: "",
              Expert_SerialNumber: "",
              Category_SerialNumber: "",
            },
          ],
        },
      },
      value1: [],
      city: [],
      rules: {
        Category_Name: [
          { required: true, message: "请输入类别名称", trigger: "blur" },
        ],
      },
      loading: false,
      category: [],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    add_business_expert_type() {
      this.form.Children.business_expert_type.push({
        Expert_Type_SerialNumber: "",
        Expert_SerialNumber: "",
        Category_SerialNumber: "",
      });
    },
    remove_business_expert_type() {
      if (this.form.Children.business_expert_type.length > 1) {
        this.form.Children.business_expert_type.pop();
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    handle(val) {
      this.form.ProvinceNumber = val[0];
      this.form.CityNumber = val[1];
      this.form.CountyNumber = val[2];
    },
    getData() {
      const that = this;
      $.ajax({
        url: absolutepath() + "utils/city.json",
        type: "GET",
        success: function (data) {
          that.city = data;
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: "business_category",
          Condition: "Row_Status = '0'",
        },
        success: function (res) {
          that.category = res;
        },
        complete: function (XMLHttpRequest) {
          that.loading = false;
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    handleRemove(file, fileList) {
      this.fileList.splice(0, 1);
    },
    handleBeforeUpload(file) {
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        //调用存储的接口放在onload中，存在异步操作
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid, //添加uid
          // 可以添加其他属性，如上传状态等
        };
        this.fileList.push(newFile);
        console.log(this.fileList);

        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.fileList), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // 返回false以阻止自动上传

      return false;
    },
    submitForm(formName) {
      console.log(this.fileList);
      if (this.fileList.length !== 0) {
        let base64Image = this.fileList[0].url;
        let dataIndex = base64Image.indexOf("data:");
        let base64Index = base64Image.indexOf(";base64,");
        let substring = base64Image.substring(dataIndex + 5, base64Index);
        let ls_split = substring.split("/");
        this.form.Picture_URL = this.fileList[0].uid + "." + ls_split[1];
      }
      this.form.ProvinceNumber = this.form.value1[0];
      this.form.CityNumber = this.form.value1[1];
      this.form.CountyNumber = this.form.value1[2];
      console.log(this.form);
      let lArray = new Array();
      lArray.push(this.form);
      let lJSONObject_business_expert = new Object();
      lJSONObject_business_expert.business_expert = lArray; //换表
      let lJSONObject_DataSet = new Object(); // Modify
      lJSONObject_DataSet.Add = lJSONObject_business_expert; //换表
      const _this = this;
      //   return;
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          if (Result.Status === "success") {
            _this.$message({
              message: "提交成功",
              type: "success",
            });
            window.history.go(-1);
          } else {
            _this.$message.error("提交失败，请稍后再试");
          }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
});
